const server = require('./server');
const fs = require('fs')

const init = async () => {
    await server.register(require('inert'));

    server.route({
        config: {
            description: '初始化',
            cors: {
                origin: ['*'],
                additionalHeaders: ['cache-control', 'x-requested-with']
            }
        },
        method: 'GET',
        path: '/{path*}',
        handler: async (request, h) => {
            let path = request.params.path;
            path = path ? `./public/${path}` : './public/index.html';
            let promise = function () {
                return new Promise((resolve, reject) => {
                    fs.exists(path, exists => {
                        if (!exists) {
                            // 静态资源不存在 
                            // 重定向
                            resolve(h.file('./public/index.html'));
                        } else {
                            // 静态资源存在
                            resolve(h.file(path));
                        }
                    })
                })
            }
            return await promise()
        }
    });

    await server.start();
    console.log(`Server running at: ${server.info.uri}`);
};

process.on('unhandledRejection', (err) => {
    console.error(err);
    process.exit(1);
});

init();